/**
 * 漫画阅读器核心JavaScript功能
 * 包含基础功能、API调用、事件处理等
 */

// 全局命名空间
window.ComicReader = window.ComicReader || {};

// 配置
ComicReader.config = {
    apiBase: '/api',
    imageQuality: 85,
    preloadPages: 2,
    cacheTimeout: 3600000, // 1小时
    touchSensitivity: 50,
    autoHideDelay: 3000,
    retryAttempts: 3,
    retryDelay: 1000
};

// 工具函数
ComicReader.utils = {
    /**
     * 防抖函数
     */
    debounce: function(func, wait, immediate) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                timeout = null;
                if (!immediate) func.apply(this, args);
            };
            const callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(this, args);
        };
    },

    /**
     * 节流函数
     */
    throttle: function(func, limit) {
        let inThrottle;
        return function(...args) {
            if (!inThrottle) {
                func.apply(this, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    },

    /**
     * 格式化文件大小
     */
    formatFileSize: function(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
    },

    /**
     * 格式化时间
     */
    formatTime: function(dateString) {
        if (!dateString) return '未知';
        
        try {
            const date = new Date(dateString);
            const now = new Date();
            const diff = now - date;
            const day = 24 * 60 * 60 * 1000;
            
            if (diff < day) {
                return '今天';
            } else if (diff < 7 * day) {
                return Math.floor(diff / day) + '天前';
            } else {
                return date.toLocaleDateString('zh-CN');
            }
        } catch (e) {
            return '未知';
        }
    },

    /**
     * 生成唯一ID
     */
    generateId: function() {
        return Date.now().toString(36) + Math.random().toString(36).substr(2);
    },

    /**
     * 检测移动设备
     */
    isMobile: function() {
        return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ||
               (window.innerWidth <= 768);
    },

    /**
     * 检测触摸设备
     */
    isTouchDevice: function() {
        return 'ontouchstart' in window || navigator.maxTouchPoints > 0;
    },

    /**
     * 获取元素的绝对位置
     */
    getElementOffset: function(element) {
        const rect = element.getBoundingClientRect();
        return {
            top: rect.top + window.pageYOffset,
            left: rect.left + window.pageXOffset,
            width: rect.width,
            height: rect.height
        };
    },

    /**
     * 平滑滚动到元素
     */
    scrollToElement: function(element, offset = 0) {
        const elementPosition = this.getElementOffset(element).top;
        const offsetPosition = elementPosition + offset;
        
        window.scrollTo({
            top: offsetPosition,
            behavior: 'smooth'
        });
    }
};

// API调用模块
ComicReader.api = {
    /**
     * 基础请求方法
     */
    request: async function(url, options = {}) {
        const defaultOptions = {
            headers: {
                'Content-Type': 'application/json'
            }
        };
        
        const finalOptions = { ...defaultOptions, ...options };
        
        try {
            const response = await fetch(ComicReader.config.apiBase + url, finalOptions);
            
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
            
            const data = await response.json();
            
            if (data.status !== 'success') {
                throw new Error(data.message || '请求失败');
            }
            
            return data.data;
        } catch (error) {
            console.error('API请求失败:', error);
            throw error;
        }
    },

    /**
     * GET请求
     */
    get: function(url) {
        return this.request(url, { method: 'GET' });
    },

    /**
     * POST请求
     */
    post: function(url, data) {
        return this.request(url, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    },

    /**
     * DELETE请求
     */
    delete: function(url) {
        return this.request(url, { method: 'DELETE' });
    },

    /**
     * 获取漫画列表
     */
    getComics: function(page = 1, limit = 20, search = '') {
        const params = new URLSearchParams({ page, limit });
        if (search) params.append('search', search);
        return this.get(`/comics?${params}`);
    },

    /**
     * 获取漫画详情
     */
    getComic: function(comicId) {
        return this.get(`/comics/${comicId}`);
    },

    /**
     * 获取章节列表
     */
    getChapters: function(comicId) {
        return this.get(`/comics/${comicId}/chapters`);
    },

    /**
     * 获取页面列表
     */
    getPages: function(chapterId) {
        return this.get(`/chapters/${chapterId}/pages`);
    },

    /**
     * 预加载缓存
     */
    preloadCache: function(chapterId, startPage = 1, pageCount = 5) {
        return this.post('/cache/preload', {
            chapter_id: chapterId,
            start_page: startPage,
            page_count: pageCount
        });
    },

    /**
     * 清除缓存
     */
    clearCache: function(type = 'all') {
        return this.delete(`/cache/clear?type=${type}`);
    },

    /**
     * 扫描漫画
     */
    scanComics: function(force = false) {
        return this.post(`/scan?force=${force}`);
    },

    /**
     * 获取系统统计
     */
    getStats: function() {
        return this.get('/stats');
    }
};

// 存储模块
ComicReader.storage = {
    /**
     * 保存到本地存储
     */
    set: function(key, value) {
        try {
            const data = {
                value: value,
                timestamp: Date.now()
            };
            localStorage.setItem('comic_reader_' + key, JSON.stringify(data));
            return true;
        } catch (e) {
            console.warn('本地存储失败:', e);
            return false;
        }
    },

    /**
     * 从本地存储获取
     */
    get: function(key, defaultValue = null) {
        try {
            const item = localStorage.getItem('comic_reader_' + key);
            if (!item) return defaultValue;
            
            const data = JSON.parse(item);
            return data.value;
        } catch (e) {
            console.warn('读取本地存储失败:', e);
            return defaultValue;
        }
    },

    /**
     * 删除本地存储
     */
    remove: function(key) {
        try {
            localStorage.removeItem('comic_reader_' + key);
            return true;
        } catch (e) {
            console.warn('删除本地存储失败:', e);
            return false;
        }
    },

    /**
     * 清空所有本地存储
     */
    clear: function() {
        try {
            const keys = Object.keys(localStorage);
            keys.forEach(key => {
                if (key.startsWith('comic_reader_')) {
                    localStorage.removeItem(key);
                }
            });
            return true;
        } catch (e) {
            console.warn('清空本地存储失败:', e);
            return false;
        }
    },

    /**
     * 保存阅读进度
     */
    saveReadingProgress: function(comicId, chapterId, pageNum, chapterTitle = '') {
        const progress = {
            comicId: comicId,
            chapterId: chapterId,
            pageNum: pageNum,
            chapterTitle: chapterTitle,
            timestamp: Date.now()
        };
        return this.set(`reading_progress_${comicId}`, progress);
    },

    /**
     * 获取阅读进度
     */
    getReadingProgress: function(comicId) {
        return this.get(`reading_progress_${comicId}`, null);
    },

    /**
     * 保存用户设置
     */
    saveSettings: function(settings) {
        return this.set('user_settings', settings);
    },

    /**
     * 获取用户设置
     */
    getSettings: function() {
        const defaultSettings = {
            imageQuality: 85,
            preloadPages: 2,
            touchSensitivity: 50,
            autoHideControls: true,
            enablePreload: true,
            saveProgress: true
        };
        
        const saved = this.get('user_settings', {});
        return { ...defaultSettings, ...saved };
    }
};

// 事件管理器
ComicReader.events = {
    listeners: {},

    /**
     * 添加事件监听器
     */
    on: function(event, callback) {
        if (!this.listeners[event]) {
            this.listeners[event] = [];
        }
        this.listeners[event].push(callback);
    },

    /**
     * 移除事件监听器
     */
    off: function(event, callback) {
        if (!this.listeners[event]) return;
        
        const index = this.listeners[event].indexOf(callback);
        if (index > -1) {
            this.listeners[event].splice(index, 1);
        }
    },

    /**
     * 触发事件
     */
    emit: function(event, data) {
        if (!this.listeners[event]) return;
        
        this.listeners[event].forEach(callback => {
            try {
                callback(data);
            } catch (e) {
                console.error('事件回调执行失败:', e);
            }
        });
    }
};

// UI组件
ComicReader.ui = {
    /**
     * 显示加载提示
     */
    showLoading: function(text = '加载中...') {
        let overlay = document.getElementById('loading-overlay');
        if (!overlay) {
            overlay = document.createElement('div');
            overlay.id = 'loading-overlay';
            overlay.className = 'loading-overlay';
            overlay.innerHTML = `
                <div class="loading-spinner">
                    <div class="spinner"></div>
                    <div class="loading-text">${text}</div>
                </div>
            `;
            document.body.appendChild(overlay);
        }
        
        const textElement = overlay.querySelector('.loading-text');
        if (textElement) textElement.textContent = text;
        
        overlay.style.display = 'flex';
    },

    /**
     * 隐藏加载提示
     */
    hideLoading: function() {
        const overlay = document.getElementById('loading-overlay');
        if (overlay) {
            overlay.style.display = 'none';
        }
    },

    /**
     * 显示消息提示
     */
    showMessage: function(message, type = 'info', duration = 5000) {
        const messageElement = document.createElement('div');
        messageElement.className = `flash-message flash-${type}`;
        messageElement.innerHTML = `
            <span class="flash-text">${message}</span>
            <button class="flash-close" onclick="this.parentElement.remove()">×</button>
        `;
        
        let container = document.querySelector('.flash-messages');
        if (!container) {
            container = document.createElement('div');
            container.className = 'flash-messages';
            document.body.appendChild(container);
        }
        
        container.appendChild(messageElement);
        
        // 自动移除
        if (duration > 0) {
            setTimeout(() => {
                if (messageElement.parentNode) {
                    messageElement.style.opacity = '0';
                    setTimeout(() => {
                        messageElement.remove();
                    }, 300);
                }
            }, duration);
        }
    },

    /**
     * 显示确认对话框
     */
    confirm: function(message, title = '确认') {
        return new Promise((resolve) => {
            if (window.confirm(message)) {
                resolve(true);
            } else {
                resolve(false);
            }
        });
    },

    /**
     * 创建模态框
     */
    createModal: function(title, content, options = {}) {
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3 class="modal-title">${title}</h3>
                    <button class="modal-close">×</button>
                </div>
                <div class="modal-body">${content}</div>
                ${options.footer ? `<div class="modal-footer">${options.footer}</div>` : ''}
            </div>
        `;
        
        document.body.appendChild(modal);
        
        // 事件处理
        const closeBtn = modal.querySelector('.modal-close');
        const overlay = modal.querySelector('.modal-overlay');
        
        const closeModal = () => {
            modal.classList.remove('active');
            setTimeout(() => modal.remove(), 300);
        };
        
        closeBtn.addEventListener('click', closeModal);
        overlay.addEventListener('click', closeModal);
        
        // 显示模态框
        setTimeout(() => modal.classList.add('active'), 10);
        
        return modal;
    }
};

// 图片加载器
ComicReader.imageLoader = {
    cache: new Map(),
    loading: new Set(),

    /**
     * 预加载图片
     */
    preload: function(src) {
        return new Promise((resolve, reject) => {
            if (this.cache.has(src)) {
                resolve(this.cache.get(src));
                return;
            }
            
            if (this.loading.has(src)) {
                // 如果正在加载，等待完成
                const checkLoading = () => {
                    if (!this.loading.has(src)) {
                        if (this.cache.has(src)) {
                            resolve(this.cache.get(src));
                        } else {
                            reject(new Error('加载失败'));
                        }
                    } else {
                        setTimeout(checkLoading, 100);
                    }
                };
                checkLoading();
                return;
            }
            
            this.loading.add(src);
            
            const img = new Image();
            
            img.onload = () => {
                this.loading.delete(src);
                this.cache.set(src, img);
                resolve(img);
            };
            
            img.onerror = () => {
                this.loading.delete(src);
                reject(new Error(`图片加载失败: ${src}`));
            };
            
            img.src = src;
        });
    },

    /**
     * 批量预加载
     */
    preloadBatch: function(srcList) {
        return Promise.allSettled(
            srcList.map(src => this.preload(src))
        );
    },

    /**
     * 清除缓存
     */
    clearCache: function() {
        this.cache.clear();
        this.loading.clear();
    }
};

// 初始化
ComicReader.init = function() {
    // 应用用户设置
    const settings = this.storage.getSettings();
    this.config = { ...this.config, ...settings };
    
    // 设置全局错误处理
    window.addEventListener('error', function(e) {
        console.error('页面错误:', e.error);
        ComicReader.ui.hideLoading();
    });
    
    // 网络状态监听
    window.addEventListener('online', function() {
        ComicReader.ui.showMessage('网络已连接', 'success', 2000);
    });
    
    window.addEventListener('offline', function() {
        ComicReader.ui.showMessage('网络已断开，部分功能可能无法使用', 'warning', 0);
    });
    
    // 触发初始化完成事件
    this.events.emit('initialized');
    
    console.log('漫画阅读器初始化完成');
};

// DOM加载完成后初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => ComicReader.init());
} else {
    ComicReader.init();
}

// 导出到全局作用域
window.showLoading = ComicReader.ui.showLoading;
window.hideLoading = ComicReader.ui.hideLoading;